/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.servlets;

import com.codemagi.util.DateUtils;
import java.io.IOException;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.Logger;

/**
 *  Adds a far-forward <code>Expires</code> header to requests to enable browser caching. 
 *  By default, this expiration date is set to three days in the future so that browsers 
 *  will only check for new versions of a file once every 3 days. 
 *
 *  @version 1.0
 *  @author August Detlefsen for CodeMagi, Inc.
 */
public final class ExpiresFilter implements Filter {

    Logger log = Logger.getLogger(this.getClass());

    private Integer expireDays = 3;

    private FilterConfig config = null;

    public void init(FilterConfig config) 
	throws ServletException {

	this.config = config;
    }


    public void destroy() {
	this.config = null;
    }


    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
	throws ServletException, IOException {

	//set the header
	try {
	    log.debug("ExpiresFilter.doFilter: " + ((HttpServletRequest)request).getRequestURL());

	    HttpServletResponse httpResponse = (HttpServletResponse)response;

	    
	    httpResponse.setDateHeader("Expires", DateUtils.addDays(new Date(), expireDays).getTime() );  //in milliseconds
	    httpResponse.setHeader("Cache-Control", "max-age=" + (expireDays * 86400) );  //in seconds //HTTP 1.1
	    httpResponse.setHeader("Pragma", "public"); //HTTP 1.0                                       

	} catch (ClassCastException cce) {
	    //no-op, just a safety measure
	}

	//forward on to other filters
	chain.doFilter(request, response);
    }

}
